package 笔试;

import java.util.HashMap;

public class 字符串替换 {
    public String token_replace(String my_template, String[] keys, String[] values) {
        HashMap<String, String> map = new HashMap<>();
        for(int i = 0; i < keys.length; i++) {
            map.put(keys[i], values[i]);
        }
        StringBuilder sb = new StringBuilder();
        int l = 0;
        while(l < my_template.length()) {
            if (l < my_template.length() && my_template.charAt(l) != '%') {
                sb.append(my_template.charAt(l));
                l++;
                continue;
            } else {
                int r = my_template.indexOf("%", l+1);
                if(r == -1) {
                    sb.append('%');
                    break;
                }
                String tmp = my_template.substring(l+1, r);
                if(map.containsKey(tmp)) {
                    sb.append(map.get(tmp));
                    l = r+1;
                } else {
                    sb.append(tmp);
                    l = r;
                }

            }
        }
        return sb.toString();
    }
}
